<script setup>
import { reactive } from 'vue';
import { userRegister } from '@/network/user'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

const router = useRouter();

const dataForm = reactive({
  userName: '',
  nickName: '',
  password: '',
  confirmPassword: '',
});

const rules = {
  userName: [
    {
      required: true,
      message: '账号不能为空',
      trigger: 'blur',
    }
  ],
  nickName: [
    {
      required: true,
      message: '昵称不能为空',
      trigger: 'blur',
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    {
      min: 8,
      message: '密码不能小于8位',
      trigger: 'blur',
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '确认密码不能为空',
      trigger: 'blur',
    },
    {
      min: 8,
      message: '确认密码不能小于8位',
      trigger: 'blur',
    }
  ]
};

const handleSubmit = async (values) => {
  if (dataForm.password !== dataForm.confirmPassword) {
    message.error("两次密码输入不一致");
    return;
  }
  const res = await userRegister(values);
  // 注册成功, 跳转到登录页面
  if (res.code === 200) {
    message.success("注册成功");
    router.push({
      path: "/user/login",
      replace: true
    });
  } else {
    message.error(res.message);
  }
};
</script>

<template>
  <div id="user-register">
    <h2 class="title">用户注册</h2>
    <a-form style="width:480px; margin: 0 auto;" label-align="left" :model="dataForm" :rules="rules" name="basic"
      :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off" @finish="handleSubmit">
      <a-form-item label="账号" name="userName">
        <a-input v-model:value="dataForm.userName" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item label="昵称" name="nickName">
        <a-input v-model:value="dataForm.nickName" placeholder="请输入昵称" />
      </a-form-item>

      <a-form-item label="密码" name="password">
        <a-input-password v-model:value="dataForm.password" placeholder="请输入密码" />
      </a-form-item>

      <a-form-item label="确认密码" name="confirmPassword">
        <a-input-password v-model:value="dataForm.confirmPassword" placeholder="请输入确认密码" />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
        <a-button type="primary" html-type="submit">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
#user-register .title {
  text-align: center;
}
</style>